package com.duowei.diandan.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.duowei.diandan.R;
import com.duowei.diandan.app.InitManager;
import com.duowei.diandan.event.DownloadStatusEvent;
import com.duowei.diandan.event.ProgressBarEvent;
import com.duowei.diandan.fragment.dialog.InputDialogFragment;
import com.duowei.diandan.service.DataSyncService;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.RuntimePermissions;

@RuntimePermissions
public class DownloadActivity extends BaseActivity {

    private Handler mHandler = new Handler();
    private ProgressBar mProgressBar;
    private TextView mProgressText;
    private Button mSettingButton;
    private Button mRetryButton;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_download);

        mProgressBar = findViewById(R.id.progressBar);
        mProgressBar.setMax(100);
        mProgressText = findViewById(R.id.progressText);
        mSettingButton = findViewById(R.id.settingButton);
        mRetryButton = findViewById(R.id.retryButton);

        mSettingButton.setOnClickListener(v -> {
            InputDialogFragment fragment = InputDialogFragment.newInstanceInputPassword();
            fragment.setOkBtnClickListener(text -> {
                if (getString(R.string.password).equals(text)) {
                    SettingsActivity.openSettingsActivity(this);
                } else {
                    Toast.makeText(this, "密码错误", Toast.LENGTH_SHORT).show();
                }
            });
            fragment.show(getSupportFragmentManager(), null);
        });

        mRetryButton.setOnClickListener(v -> {
            DownloadActivityPermissionsDispatcher.startDownloadWithPermissionCheck(this);
        });

        mHandler.postDelayed(() -> {
            DownloadActivityPermissionsDispatcher.startDownloadWithPermissionCheck(this);
        }, 1000);

        InitManager.getInstance().start();
        InitManager.getInstance().setCanDownTime(false);

        EventBus.getDefault().register(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void showMessage(ProgressBarEvent event) {
        if (event.progress > 0) {
            mProgressBar.setProgress(event.progress);
        } else {
            mProgressBar.setProgress(0);
        }

        mProgressText.setText(event.message);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void downloadComplete(DownloadStatusEvent event) {
        if (DownloadStatusEvent.Status.ERROR == event.status) {
            mSettingButton.setVisibility(View.VISIBLE);
            mRetryButton.setVisibility(View.VISIBLE);

        } else if (DownloadStatusEvent.Status.SUCCESS == event.status) {
            Intent intent = new Intent(this, WelcomeActivity.class);
            startActivity(intent);
            finish();
        }
    }

    @NeedsPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
    public void startDownload() {
        mSettingButton.setVisibility(View.INVISIBLE);
        mRetryButton.setVisibility(View.INVISIBLE);

        startService(new Intent(this, DataSyncService.class));
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        DownloadActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }
}
